package com.qdaily.ui.ui.views;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.view.MotionEventCompat;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.qdaily.supportlibrary.util.ImageUtil;
import com.qdaily.supportlibrary.util.LocalDisplay;
import com.qdaily.supportlibrary.util.QLog;
import com.qdaily.ui.R;
import com.qdaily.ui.controller.ActivityController;
import com.qdaily.ui.data.DataBase.ReadDAO;
import com.qdaily.ui.net.QDEnum;
import com.qdaily.ui.net.model.ArticleInfo;
import com.qdaily.ui.net.model.ArticleMeta;

import java.lang.ref.WeakReference;
import java.util.List;

/**
 * Created by song on 15/5/4.
 */
public class ArticleInfoController implements View.OnTouchListener, View.OnClickListener, ImageLoadingListener {
    private Context mContext;
    private ArticleInfo articleInfo;
    private View articleInfoView;
    private LayoutInflater inflater;

    private int smallImageHeight;
    private int bigImageHeight;
    private int paddingInner;
    private int paddingLeft;
    private int paddingTop;

    private TextView commentCountTextView;
    private View article_recommond1;
    private View article_recommond2;
    private View article_recommond3;
    private View article_recommond4;
    private View article_recommond5;

    private boolean delayFlag;

    private boolean isShowArticle = false; //暂时关闭

    public ArticleInfoController(Context context) {
        this.mContext = context;
        inflater = LayoutInflater.from(context);
        calDimen();
        delayHandler = new DelayHandler(mContext);
    }

    private View getUnUserRecommendView(int i) {
        if (i > 5)
            return null;
        View view = null;
        switch (i) {
            case 0:
                view = article_recommond1;
                break;
            case 1:
                view = article_recommond2;
                break;
            case 2:
                view = article_recommond3;
                break;
            case 3:
                view = article_recommond4;
                break;
            case 4:
                view = article_recommond5;
                break;
        }
        return view;
    }

    @Nullable
    private List<ArticleMeta> getRecommendList(int i) {
        if (i > 5 || articleInfo == null)
            return null;
        List<ArticleMeta> result = null;
        switch (i) {
            case 0:
                result = articleInfo.getRecommend();
                break;
            case 1:
                result = articleInfo.getRecommend_two();
                break;
            case 2:
                result = articleInfo.getRecommend_three();
                break;
            case 3:
                result = articleInfo.getRecommend_four();
                break;
            case 4:
                result = articleInfo.getRecommend_five();
                break;
        }
        return result;
    }

    private void configCommendView() {
        for (int i = 0; i < 5; i++) {
            List<ArticleMeta> recommendList = getRecommendList(i);
            if (recommendList != null) {
                ArticleMeta resultArticleMeta = null;
                int count = recommendList.size();
                for (int j = count - 1; j >= 0; j--) {
                    resultArticleMeta = recommendList.get(j);
                    if (!ReadDAO.getInstance().isRead(resultArticleMeta.getPost().getId(), QDEnum.DetailEnum.ARTICLE.value)) {
                        break;
                    }
                }

                if (resultArticleMeta == null)
                    continue;
                View recommendView = getUnUserRecommendView(i);
                if (recommendView != null) {
                    TextView recommendText = (TextView) recommendView.findViewById(R.id.articleInfoRecommend_Textview);
                    recommendText.setText(resultArticleMeta.getPost().getTitle());

                    ImageView recommendImage = (ImageView) recommendView.findViewById(R.id.articleInfoRecommend_Imageview);
                    ImageUtil.getInstance().displayImage(resultArticleMeta.getImage(), recommendImage);

                    recommendView.setTag(resultArticleMeta);
                    recommendView.setOnClickListener(this);
                }
            }
        }
    }

    public View getArticleInfoView(ArticleInfo articleInfo) {
        if (articleInfoView == null) {
            this.articleInfo = articleInfo;
            articleInfoView = inflater.inflate(R.layout.article_info_view, null);

            ViewGroup recommondLayout = (ViewGroup) articleInfoView.findViewById(R.id.articleInfoRecommendLayout);
            recommondLayout.setLayoutParams(new LinearLayout.LayoutParams(LocalDisplay.SCREEN_WIDTH_PIXELS, bigImageHeight + smallImageHeight + paddingTop * 2 + paddingInner));

            article_recommond1 = recommondLayout.findViewById(R.id.article_recommond1);
            article_recommond1.findViewById(R.id.articleInfoRecommend_fg).setBackgroundResource(R.drawable.recommend_fg_big);
            article_recommond2 = recommondLayout.findViewById(R.id.article_recommond2);
            article_recommond2.findViewById(R.id.articleInfoRecommend_fg).setBackgroundResource(R.drawable.recommend_fg_small);
            article_recommond3 = recommondLayout.findViewById(R.id.article_recommond3);
            article_recommond3.findViewById(R.id.articleInfoRecommend_fg).setBackgroundResource(R.drawable.recommend_fg_small);
            article_recommond4 = recommondLayout.findViewById(R.id.article_recommond4);
            article_recommond4.findViewById(R.id.articleInfoRecommend_fg).setBackgroundResource(R.drawable.recommend_fg_small);
            article_recommond5 = recommondLayout.findViewById(R.id.article_recommond5);
            article_recommond5.findViewById(R.id.articleInfoRecommend_fg).setBackgroundResource(R.drawable.recommend_fg_small);

            article_recommond1.setLayoutParams(new LinearLayout.LayoutParams(bigImageHeight, bigImageHeight));
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(bigImageHeight, smallImageHeight);
            params.setMargins(0, paddingInner, 0, 0);
            article_recommond2.setLayoutParams(params);
            article_recommond3.setLayoutParams(new LinearLayout.LayoutParams(bigImageHeight, smallImageHeight));
            article_recommond4.setLayoutParams(params);
            article_recommond5.setLayoutParams(params);

            commentCountTextView = (TextView) articleInfoView.findViewById(R.id.article_commentcount);
            setCommentCount(articleInfo.getPost().getComment_count());
            if (isShowArticle) {
                View layout = articleInfoView.findViewById(R.id.articleInfoRelativeLayout);
                layout.setVisibility(View.VISIBLE);
                TextView articleName = (TextView) articleInfoView.findViewById(R.id.article_name);
                articleName.setText(articleInfo.getAuthor().getName());
                ImageView avatar = (ImageView) articleInfoView.findViewById(R.id.article_avatar);
                ImageUtil.getInstance().displayImage(articleInfo.getAuthor().getAvatar(), avatar, this);
            } else {
                View layout = articleInfoView.findViewById(R.id.articleInfoRelativeLayout);
                layout.setVisibility(View.GONE);
            }

            configCommendView();
        } else {
            if (this.articleInfo != articleInfo) {
                this.articleInfo = articleInfo;
                //TODO 更新
            }
        }
        return articleInfoView;
    }

    public void setCommentCount(int count) {
        if (commentCountTextView == null)
            return;

        if (count <= 0) {
            commentCountTextView.setVisibility(View.GONE);
        } else {
            commentCountTextView.setVisibility(View.VISIBLE);
            commentCountTextView.setText(String.format(mContext.getResources().getText(R.string.comments_number).toString(), count));
        }
    }

    private void calDimen() {
        int width = LocalDisplay.SCREEN_WIDTH_PIXELS;
        paddingInner = mContext.getResources().getDimensionPixelOffset(R.dimen.article_recommend_innermargin);
        paddingLeft = mContext.getResources().getDimensionPixelOffset(R.dimen.article_paddingLeft);
        paddingTop = mContext.getResources().getDimensionPixelOffset(R.dimen.article_recommend_paddingTop);
        bigImageHeight = (width - paddingLeft * 2 - paddingInner) / 2;
        smallImageHeight = (bigImageHeight - paddingInner) / 2;
    }

    @Override
    public void onClick(View view) {

        Object obj = view.getTag();
        if (obj != null) {
            if (obj.getClass() == ArticleMeta.class) {
                ArticleMeta recommend = (ArticleMeta) obj;

                if (mContext != null && recommend != null) {
                    ActivityController.DisplayDetailActivity(mContext, recommend);
                }
            } else {

            }
        }
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        final int action = MotionEventCompat.getActionMasked(motionEvent);

        QLog.w("articleInfoView的点击", "action:" + action);

        delayFlag = true;
        Object obj = view.getTag();
        if (obj != null) {
            if (obj.getClass() == ArticleMeta.class) {
                ArticleMeta recommend = (ArticleMeta) obj;
                DelayThread delayThread = new DelayThread(recommend);
                delayThread.start();
            } else {

            }
        }
        return false;
    }

    public void stopDelayThread() {
        delayFlag = false;
    }

    private DelayHandler delayHandler;

    private final static int MsgArticleWhat = 1001;

    private static class DelayHandler extends Handler {
        private final WeakReference<Context> contextWeakReference;

        public DelayHandler(Context context) {
            contextWeakReference = new WeakReference<Context>(context);
        }

        @Override
        public void handleMessage(Message msg) {
            if (msg.what == MsgArticleWhat) {
                ArticleMeta recommend = (ArticleMeta) msg.obj;
                Context context = contextWeakReference.get();

                if (context != null && recommend != null) {
                    ActivityController.DisplayDetailActivity(context, recommend);
                }
            }

        }
    }

    class DelayThread extends Thread {
        ArticleMeta recommend;

        public DelayThread(ArticleMeta recommend) {
            this.recommend = recommend;
        }

        @Override
        public void run() {
            try {
                Thread.sleep(500);
                if (delayFlag) {
                    delayHandler.sendMessage(delayHandler.obtainMessage(MsgArticleWhat, recommend));
                    QLog.w("DelayThread", "delayFlag为true");
                } else {
                    QLog.w("DelayThread", "delayFlag为false");
                }
            } catch (Exception e) {

            }
        }
    }

    @Override
    public void onLoadingStarted(String imageUri, View view) {

    }

    @Override
    public void onLoadingFailed(String imageUri, View view, FailReason failReason) {

    }

    @Override
    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {

    }

    @Override
    public void onLoadingCancelled(String imageUri, View view) {

    }
}
